import { getCircleStudyPlanDetail, getFixedStudyPlanDetail } from '@/api/Plan';
import CusDrawer from '@/components/CusDrawer';
import ResourceNameForTable from '@/components/resourceLibraryComp/ResourceNameForTable';
import { subjectOptionsMap } from '@/components/StudyObjectSelect/data.tsx';
import {
  EStudyPackageResourceNameType,
  EStudyPackageResourceType,
} from '@/pages/PlanManage/AddStudyPlan/components/interface';
import type { IStudyPackage } from '@/pages/PlanManage/AddStudyPlan/interface';
import { Button, Descriptions, Spin } from 'antd';
import { isEmpty } from 'lodash-es';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { v4 as uuid } from 'uuid';
import CourseWareDetailForPlan from './CourseWareDetailForPlan';
import OStyle from './index.less';
import TestPaperDetailForPlan from './TestPaperDetailForPlan';
const DRAWERWIDTH = 680;

function StudyPlanDetail(props: { planCourseId: string; planType: string }) {
  const { planCourseId, planType } = props;
  const [loading, setLoading] = useState(false);
  const [planDetail, setPlanDetail] = useState<Record<string, any>>();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [currRowResourceId, setCurrRowResourceId] = useState<string>();
  const [currType, setCurrType] = useState<number>(); // '100':视频课件， '200':图文课件， '300':试卷， '400':pdf课件

  useEffect(() => {
    if (!planCourseId) return;
    setLoading(true);
    let request: any;
    if (planType === '200') {
      request = getCircleStudyPlanDetail(planCourseId);
    } else {
      request = getFixedStudyPlanDetail(planCourseId);
    }
    request
      .then((res: any) => {
        const { data } = res;
        //学习包
        data.studyPackageList = data.studyPackageList.reduce(
          (prev: IStudyPackage[], curr: IStudyPackage, index: number, array: IStudyPackage[]) => {
            const { studyList, examList, packageType, sourceType } = curr;
            let newStudyList: any[] = studyList || [];
            if (!isEmpty(examList)) {
              newStudyList = [...newStudyList, ...examList!];
            }
            prev.push({ id: uuid(), studyList: newStudyList, packageType, sourceType, isCharge: data.isCharge });
            return prev;
          },
          [],
        );
        setPlanDetail(data);
      })
      .catch((err: any) => {
        console.log('--StudyPlanDetail--getFixedStudyPlanDetail/getCircleStudyPlanDetail--err--:', err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [planCourseId]);

  //课件详情drawer 配置
  // 该详情也要区分 是boss 还是 企业/协会
  const drawerConfig = useMemo(() => {
    if (!currRowResourceId || !currType) return;
    let DrawerChild, title;
    if (currType === 300) {
      title = '试卷详情';
      DrawerChild = <TestPaperDetailForPlan coursewareId={currRowResourceId} />;
    } else {
      title = '课件详情';
      DrawerChild = <CourseWareDetailForPlan coursewareId={currRowResourceId} />;
    }
    return {
      title,
      width: DRAWERWIDTH,
      open: drawerOpen,
      onClose: () => {
        setDrawerOpen(false);
      },
      destroyOnClose: true,
      children: DrawerChild,
    };
  }, [currRowResourceId, drawerOpen, currType]);

  const getSubjectText = useCallback(
    (studyObjectStr: string) => {
      if (isEmpty(studyObjectStr)) {
        return '';
      }
      return studyObjectStr
        .split(',')
        .map((code: string) => subjectOptionsMap[code as keyof typeof subjectOptionsMap])
        .join(',');
    },
    [currRowResourceId, subjectOptionsMap],
  );

  return (
    <>
      <CusDrawer {...drawerConfig} />
      {!isEmpty(planDetail) && (
        <Spin spinning={loading}>
          <Descriptions
            title="基本信息"
            labelStyle={{ width: 72, justifyContent: 'flex-end' }}
            column={2}
            className="ym_descriptions"
          >
            <Descriptions.Item label="计划名称" span={1}>
              {planDetail.title}
            </Descriptions.Item>
            <Descriptions.Item label="分类" span={1}>
              {planDetail.parClassName + '/' + planDetail.className}
            </Descriptions.Item>
            <Descriptions.Item label="类型" span={1}>
              {planType === '200' ? '周期循环' : '固定时间'}
            </Descriptions.Item>
            <Descriptions.Item label="学习对象" span={1}>
              {planDetail.objectType === 1 ? (
                <span>{getSubjectText(planDetail.studyObject)}</span>
              ) : (
                <span>
                  {planDetail.serviceNumType === 2
                    ? '非管辖企业人员'
                    : planDetail.serviceNumType === 1
                    ? '管辖企业人员'
                    : '全部范围人员'}
                </span>
              )}
            </Descriptions.Item>

            {planType === '200' && (
              <Descriptions.Item label="学习机制" span={1}>
                {planDetail.courseRuleDto.studyModel === 200 ? '顺序轮学' : '随机抽学'}
              </Descriptions.Item>
            )}
            <Descriptions.Item label="学习时间" span={1}>
              {planType === '200' ? (
                <span>{`${planDetail.courseEffectiveDto.studyTime}点至${planDetail.cycleTime}日后${planDetail.courseEffectiveDto.studyTime}点`}</span>
              ) : (
                <span>
                  {planDetail.startTime}-{planDetail.endTime}
                </span>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间" span={1}>
              {planDetail.createTime}
            </Descriptions.Item>
          </Descriptions>
          <Descriptions
            title="学习内容"
            labelStyle={{ width: 72, justifyContent: 'flex-end' }}
            column={2}
            className="ym_descriptions"
          >
            <Descriptions.Item label="" span={2} style={{ width: '100%' }}>
              <div style={{ width: '698px', padding: '0 16px' }}>
                {planDetail.studyPackageList.map((pItem: any, pIndex: number) => (
                  <ul key={pItem.id} className={OStyle.package_content_list}>
                    {pItem.studyList.map((listItem: any, listIndex: number) => (
                      <li className={OStyle.list_item} key={listItem.coursewareId}>
                        <ResourceNameForTable
                          title={listItem.name}
                          resourceType={0}
                          resourceFrom={EStudyPackageResourceType[Number(listItem.type)] as any}
                        />
                        <p className={OStyle.item_right}>
                          <span className={OStyle.right_text}>
                            {EStudyPackageResourceNameType[Number(listItem.type)]}
                          </span>
                          <Button
                            type="text"
                            size="small"
                            onClick={(e: React.MouseEvent) => {
                              e.stopPropagation();
                              console.log('--pItem.isCharge--企业才有付费限制--:', pItem.isCharge);
                              setCurrRowResourceId(listItem.coursewareId);
                              setCurrType(listItem.type);
                              setDrawerOpen(true);
                            }}
                          >
                            <span className="safe-edu_table_operation_text">详情</span>
                          </Button>
                        </p>
                      </li>
                    ))}
                  </ul>
                ))}
              </div>
            </Descriptions.Item>
          </Descriptions>
        </Spin>
      )}
    </>
  );
}

export default StudyPlanDetail;
